﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace AppSocketControl.NOTUSE
{
    
    public class UdpServer
    {
        private Socket udpServer;

        public UdpServer(IPEndPoint serverIP)
        {
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);

            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            EndPoint endPoint = (EndPoint)iPEndPoint;
            int index = 0;
            new Thread(() =>
            {
                while(true)
                {
                    byte[] data = new byte[1024];
                    int length = 0;
                    try
                    {
                        length = udpServer.ReceiveFrom(data, ref endPoint);
                        string msg = Encoding.UTF8.GetString(data, 0, length);
                        Console.WriteLine(msg);
                        //    while (true)
                        { 
                            string sendStr = "BXL:" + (index++);
                            Byte[] sendBytes2 = Encoding.Default.GetBytes(sendStr);
                            udpServer.SendTo(sendBytes2, endPoint);
                            Console.WriteLine("Send To : " + endPoint + "    "+ sendStr);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        break;
                    }
                }
            }).Start();
        }
        
    }
}
